package com.example.demo.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.example.demo.common.MsgActionEnum;
import com.example.demo.entity.DataContent;
import com.example.demo.entity.Message;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final Logger logger = LoggerFactory.getLogger(MyWebSocketHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与客户端建立连接，通道开启");

        //添加到channelGroup
        MyChannelHandlerPool.channelGroup.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与客户端断开连接，通道关闭！");
        //添加到channelGroup 通道组
        MyChannelHandlerPool.channelGroup.remove(ctx.channel());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        /**
         * 在这里判断是第一次连接还是怎么的
         * **/
        System.out.println("-------channelRead读取数据----");
//        if(msg != null && msg instanceof FullHttpRequest){
//            FullHttpRequest request = (FullHttpRequest) msg;
//            String uri = request.uri();
//
//            Map paramMap = getUrlParams(uri);
//            System.out.println("接收到的参数是："+ JSON.toJSONString(paramMap));
//
//            //如果url包含参数，需要处理
//            if(uri.contains("?")){
//                String newUri=uri.substring(0,uri.indexOf("?"));
//                System.out.println(newUri);
//                request.setUri(newUri);
//            }
//        }else if(msg instanceof TextWebSocketFrame){
//            //正常的TEXT消息类型
//            TextWebSocketFrame frame = (TextWebSocketFrame) msg;
//            System.out.println("客户端收到服务器数据：" +frame.text());
//            sendAllMessage(frame.text());
//        }
    }

    private static Map getUrlParams(String url){
        Map<String,String> map = new HashMap<>();
        url = url.replace("?",";");
        if (!url.contains(";")){
            return map;
        }
        if (url.split(";").length > 0){
            String[] arr = url.split(";")[1].split("&");
            for (String s : arr){
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                map.put(key,value);
            }
            return  map;

        }else{
            return map;
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
        System.out.println("-------channelRead0读取数据----");
        String content = textWebSocketFrame.text();
        DataContent dataContent = JSON.parseObject(content,DataContent.class);
        Integer action = dataContent.getAction();
        //连接，前端初始化后发送一个连接动作
        if (action == MsgActionEnum.CONNECT.type){
            if(MyChannelHandlerPool.channelMap.containsKey(dataContent.getUserId())){
                MyChannelHandlerPool.channelMap.remove(dataContent.getUserId());
            }
            MyChannelHandlerPool.channelMap.put(dataContent.getUserId(),ctx.channel());

        }else if(action == MsgActionEnum.KEEPALIVE.type){

        }
    }

    public void sendAllMessage(String message){
        //收到信息后，群发给所有channel
        MyChannelHandlerPool.channelGroup.writeAndFlush( new TextWebSocketFrame("服务端收到："+message));
    }

    /**
     * 服务端推送消息给用户
     * 当用户被点赞、评论
     * **/
    public void notify(String userId,Message message){

        if(MyChannelHandlerPool.channelMap.get(userId) != null){
            MyChannelHandlerPool.channelMap.get(userId).writeAndFlush(new TextWebSocketFrame(JSONArray.toJSONString(message)));
        }else{
            logger.info("------------用户不在线----------");
        }
    }

    /**
     * 服务端给所有用户推送消息
     * 一般是公告之类的
     * **/
    public void notifyForAll(Message message){
        MyChannelHandlerPool.channelGroup.writeAndFlush(new TextWebSocketFrame(JSONArray.toJSONString(message)));
    }
}
